﻿$(function () {
    $(".login-button").click(function () {
        manageLogin();
    });
    $("#txt-password").keyup(function (e) {
        if (e.keyCode == 13) { manageLogin(); }
    });
    $("#txt-username").focus();
});

function manageLogin() {
    if ($(".login-button").html() == "登　录") {
        var username = $("#txt-username").val(),
            password = $("#txt-password").val();

        if (ruleUserName(username)) {
            if (rulePassWord(password)) {
                ajaxLogin(username, password);
            }
        }
    }
}

function ruleUserName(username) {
    if (!/^[a-zA-Z][a-zA-Z0-9_]{3,15}$/i.test(username)) {
        alert("用户名不合法，字母开头，允许4-16字节，允许字母数字下划线");
        return false;
    }
    return true;
}

function rulePassWord(password) {
    if (password.length < 6 || password.length > 16) {
        alert("密码长度在6-16字节之间");
        return false;
    }
    return true;
}

function ajaxLogin(username, password) {
    $.ajax({
        url: "/manage/authorize/login",
        type: "post", data: {
            username: username,
            password: password
        },
        beforeSend: function () {
            $(".login-button").html("请稍后...");
            $("#txt-username").attr("readonly", "readonly");
            $("#txt-password").attr("readonly", "readonly");
        },
        complete: function (request) {
            if (request.status == 200) {
                try {
                    result = JSON.parse(request.responseText);
                } catch (e) {                    
                    alert("系统错误，请稍后再试!");
                    console.info(result); return;
                }
                if (result.success) {
                    $(".login-button").html("登录成功");
                    location.href = "/manage/home/index";
                    return false;
                }
                else { alert(result.message); }
            }
            else { alert("系统错误，请稍后重试！"); }
            $(".login-button").html("登　录");
            $("#txt-username").removeAttr("readonly");
            $("#txt-password").removeAttr("readonly");
        },
        success: function (result) { },
        error: function (request, status, thrown) { }
    });
}